import Vue from 'vue'
import ElementUI from 'element-ui'
import axios from 'axios'
import config from '@/config'
import router from '@/router'
import store from '@/store'
Vue.use(ElementUI)
let TkAjax = axios.create({
  baseURL: config.baseUrl
})
window._tkAjax = TkAjax
Vue.prototype.$tkAjax = TkAjax
Vue.prototype.$tkAjaxGlobal = TkAjax.defaults
Vue.prototype.$axios = axios
TkAjax.interceptors.request.use(
  config => {
    if (store.state.token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers['x-auth-token'] = `${store.state.systemId}_${store.state.userId}_${store.state.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })
TkAjax.interceptors.response.use(function (res) {
  // console.log(res.data.code)
  if (res.data.code === '200') {
    return res
  } else if (res.data.code === '401') {
    router.replace('/login')
    return Promise.reject(res)
  } else {
    return Promise.reject(res)
  }
})
router.beforeEach(function (to, from, next) {
  if (!to.meta.ziduan && !store.state.token) {
    next('/login')
  } else {
    next()
  }
})
export default new Promise(function (resolve) {
  // store.state.settled === '0' 待提交
  // store.state.settled === '1' 待审核
  // store.state.settled === '2' 已通过
  // store.state.settled === '3' 已驳回
  if (store.state.token) {
    TkAjax.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    store.dispatch('getUserInfo').then(() => {
      router.onReady(() => {
        if (!router.currentRoute.ziduan && store.state.settled === '8') {
          router.replace('/login')
        } else if (!router.currentRoute.ziduan && !router.currentRoute.settled && store.state.settled === '') {
          router.replace('/submitdata')
        } else if (!router.currentRoute.ziduan && !router.currentRoute.settled && store.state.settled === '0') {
          router.replace('/unsubmit')
        }
      })
      router.beforeEach(function (to, from, next) {
        // console.log(store.state.settled)
        if (!to.meta.ziduan && !to.meta.settled && store.state.settled === '') {
          next('/submitdata')
        } if (!to.meta.ziduan && !to.meta.settled && store.state.settled === '0') {
          next('/unsubmit')
        } else if (!to.meta.ziduan && store.state.settled === '8') {
          next('/login')
        } else {
          next()
        }
      })
      resolve()
    })
  } else {
    resolve()
  }
})
